/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-03 22:41:28
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-04 10:18:03
 * @FilePath: /110/50/chat.server/MessageRoute.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <vector>
#include <string>
#include "InetAddr.hpp"
#include <set>
#include <sys/types.h>
#include <sys/socket.h>

#include "InetAddr.hpp"
#include "ThreePool.hpp"

#include <functional>
#include "LockGuard.hpp"

using task_t = std::function<void()>;

class MessageRoute
{
private:
    bool isExists(const InetAddr &addr)
    {
        for (auto a : _online_user)
        {
            if (a == addr)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr); // 初始化互斥锁
    }
    // 添加用户
    void AddUser(const InetAddr &addr)
    {
        LockGuard lock(&_mutex); // 加锁
        if (isExists(addr))
            return;
        _online_user.push_back(addr); // 插入用户
    }
    // 删除用户
    void DelUser(const InetAddr &addr)
    {
        LockGuard lock(&_mutex); // 加锁
        for (auto iter = _online_user.begin(); iter != _online_user.end(); ++iter)
        {
            if (*iter == addr)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }
    // 遍历用户发送消息
    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard lock(&_mutex); // 加锁
        std::string send_message = "[" + who.IP() + ":" + std::to_string(who.Port()) + "]# " + message + "\n";
        // 遍历在线用户，发送消息
        for (auto user : _online_user)
        {
            // 发送消息
            struct sockaddr_in clientaddr = user.Addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }

    // 转发消息
    void Route(int sockfd, std::string message, InetAddr who)
    {
        // 1. 我们任务，用户首次发消息，不光光是发消息，还要将自己，插入到在线用户中！
        AddUser(who);

        //
        if (message == "Q" || message == "QUIT") // 退出
        {
            DelUser(who);
        }
        // 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(&MessageRoute::RouteHelper, this, sockfd, message, who);
        // 任务入队列
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex); // 销毁互斥锁
    }

private:
    std::vector<InetAddr> _online_user; // 在线用户
    pthread_mutex_t _mutex;             // 锁
};